package com.ecity.net {
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	/**
	 * ...
	 * @author yicheng.zhang
	 */
	public class Connector extends Socket	{
		private var response:String;

		
		public function Connector(host:String="127.0.0.1",port:int=8888) {
			super(host, port);
			configureListeners();
		}
		
		private function configureListeners():void {
			addEventListener(Event.CLOSE, closeHandler);
			addEventListener(Event.CONNECT, connectHandler);
			addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}

		private function writeln(str:String):void {
			str += "\n";
			try {
				var bytes:ByteArray= new ByteArray();         
				bytes.writeUTFBytes(str);         
				writeBytes(bytes);         
				flush();  
			}
			catch(e:IOErrorEvent) {
				trace(e);
			}
		}

		private function sendRequest():void {
			trace("sendRequest");
			response = "";
			writeln("sssssssssss");
			//writeln("GET /");
			flush();
		}

		private function readResponse():void {
			var str:String = readUTFBytes(bytesAvailable);
			response += str;
		}

		private function closeHandler(event:Event):void {
			trace("closeHandler: " + event);
			trace(response.toString());
		}

		private function connectHandler(event:Event):void {
			trace("connectHandler: " + event);
			sendRequest();
		}

		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
		}

		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}

		private function socketDataHandler(event:ProgressEvent):void {
			trace("socketDataHandler: " + event);
			trace(this.readUTF()+"-------x-------------");
			readResponse();
		}
		
		
	}

}